# backend/crud/borrow_crud.py
import datetime
from sqlalchemy.orm import Session
from backend.models import BorrowRecord


def create_borrow_request(db: Session, book_id: int, borrower_id: int):
    db_request = BorrowRecord(
        book_id=book_id,
        borrower_id=borrower_id,
        status=0,  # 预约中
        borrow_date=datetime.datetime.now(datetime.UTC)
    )
    db.add(db_request)
    db.commit()
    db.refresh(db_request)
    return db_request


def approve_borrow_request(db: Session, record_id: int, lender_id: int):
    db_record = db.query(BorrowRecord).filter(BorrowRecord.id == record_id).first()
    if db_record:
        db_record.status = 1  # 借出中
        db_record.lender_id = lender_id
        db.commit()
        db.refresh(db_record)
    return db_record


def mark_as_returned(db: Session, record_id: int):
    db_record = db.query(BorrowRecord).filter(BorrowRecord.id == record_id).first()
    if db_record:
        db_record.status = 2  # 已归还
        db_record.return_date = datetime.utcnow()
        db.commit()
        db.refresh(db_record)
    return db_record


def get_borrow_queue(db: Session, book_id: int):
    return db.query(BorrowRecord).filter(
        BorrowRecord.book_id == book_id,
        BorrowRecord.status == 0  # 只获取预约中的记录
    ).order_by(BorrowRecord.borrow_date.asc()).all()


def get_borrow_record(db: Session, record_id: int):
    """根据ID获取借阅记录"""
    return db.query(BorrowRecord).filter(BorrowRecord.id == record_id).first()
